(function () {	
    var nameSpace = 'field_5840803754745916733';
    if (window[nameSpace]) return;
    var component = function (option) {
        this.initData(option);
        this.render();
        this.initDocument();//初始化监听和写入到表单
    }
    component.prototype={//原型构建
    		//初始化数据方法
    		initData:function(option){
    			this.option = option;
    			this.id = option.id || option.privateId;
    			this.field = option.field || option.getData;
		      	this.parentEl = option.el || document.getElementById(option.privateId);
		      	this.adapter = option.adaptation; // pc
		      	this.toolkit = option.toolkit; // mobile sdk
		      	this.isMobile = !!option.toolkit;
		      	this.servPath = 'cap4/BindUrlControl/getRequestURL';
		      	if (!this.isMobile) this.servPath = '/seeyon/rest/' + this.servPath;
		      	this._events = [];
		        this._shadow = document.createElement('div');
		        this.customParam = this.field.customFieldInfo.customParam
    		},
    		//渲染数据
    		render:function(){
    			var layoutStyle = this.isMobile ? 'padding: 10px 20px;' : '';
    			var baseStyle = this.isMobile ? 'font-size:16px;height:30px;line-height:30px;' : 'font-size:14px;height:24px;line-height:24px;cursor:pointer;';
    			var displayStyle = baseStyle + 'background-color: #fff;border-radius: 15px;text-align: center;color: #1f85ec;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;border: 1px solid transparent;';
    			if (this.field.ctrlBorderStyle === 'all') {
    				displayStyle += 'border-color: #1f85ec;';
    			}
    			var label = this.field.display;
    			if (this.field.auth === 'hide') layoutStyle += 'display:none;';
    			var html = '<div style="' + layoutStyle +'"><div style="' + displayStyle + '"> ' + escapeHtml(label) + '</div></div>';
    			this._shadow.innerHTML = html;
    			var el = this._shadow.childNodes[ 0 ];
    			this.el = el;
    		},
    		initDocument:function(){
    			var componentData = this;
    		    this.registerEvent(this.el, this.isMobile ? 'tap' : 'click', function () {
    		    	if (!componentData.customParam||!componentData.customParam.bindUrlField.fieldName) {
    		    		return componentData.alert("未绑定控件，请联系管理员查看。");
    		    	}
					var formPreSubmitData = componentData.preSubmitData();
					param={};
 	    		    param.masterId=formPreSubmitData.content.contentDataId;
 	    		    param.fieldName=componentData.customParam.bindUrlField.fieldName;
 	    		    param.formId = componentData.customParam.bindUrlField.formId;
 	    		    var operation = componentData.isMobile ? CAP.Form.getOperation() : componentData.adapter.getCurrentFormMode();
 	    	        var data =( operation === 'browse' ? null : formPreSubmitData);
 	    	        param.data=data;
 	    		    if (componentData.field.formType=="formson") {
 	    		    	 param.subRecordId=componentData.field.recordId;
 	    		    	 param.formName=componentData.option.formMessage.tableName;
 					}
 	    		    var callBack = function (res) {
                         if (res.success || res.code == "0") {
                        	 if (componentData.isMobile) {
                        		 cmp.dialog.loading(false);
							}
                            var url = res.data.url;
                            if (url) {
                             	return componentData.openUrl(url);
                            }
                          }
                         return componentData.alert("未获取到链接地址，请联系管理员查看。");
                      };
                    componentData.excute(callBack);
		    		return;
    		    });
    		    this.parentEl.appendChild(this.el);
    		},
    		//注册监听
    		registerEvent:function(el,type,handler){
    			var detach = function () {
    		        el.removeEventListener(type, handler, false);
    		      };
    		    el.addEventListener(type, handler, false);
    		    this._events.push(detach);
    		    return detach;
    		},
    		excute:function(fn){
	    		var requestPath =this.servPath;
    		    if (!this.isMobile) {
    		    	var proce  = top.$.progressBar({ text: "正在跳转请稍等"});
    		    	$.ajax({
                         type: "POST",
                         url: requestPath,
                         data:JSON.stringify(param),
                         dataType: "json",
                         contentType:"application/json",
                         success:fn ,
                         complete: function () {
                        	 proce.close();
                         },
                         error: function (e) {
                        	 proce.close();
                         }
                     });
				}else{
				    cmp.dialog.loading("正在跳转请稍等");
					var method = errorBuilder({
				        success :fn,
				        error:function(e){
				        	cmp.dialog.loading(false);
				        }
					});
					method.complete=function () {
						proce.close();
					}
					SeeyonApi.Rest.post(requestPath,'',param,cmp.extend({},method));
				}
    		},
    		preSubmitData:function(){
    			if (this.isMobile) {
    		        return CAP.Form.createSubmitData();
    		      } else {
    		        var data;
    		        this.adapter.callTakeFormSave({
    		          type: 'save',
    		          isPrev: true,
    		          state: 'getFormAllData',
    		          callback: function (result) {
    		            data = result;
    		          }
    		        }, this.id);
    		        return data;
    		      }
    		},
    		openUrl:function(url){
    			if (this.isMobile) {
    				cmp.openWebView({
    			        url: url,
    			        isNew: true,
    			        header: "header",
    			        useNativebanner:false, //是否显示原生导航栏
    			        "iOSStatusBarStyle":"", // ios状态栏颜色0=黑色 1=白色
    			        success: null,
    			        error: null
    			    });
    		      } else {
                 	 this.adapter.openWindow(url);
    		      }
    		},
    		alert:function(message){
    			if (this.isMobile) {
    		        return this.toolkit.alert({ text:message});
    		      } else {
    		    	return  $.alert(message);
    		      }
    		},
    		destroy: function () {
    		    if (this.el.parentNode) this.el.parentNode.removeChild(this.el);
    		    this.removeEvents();
    		    this.el = null;
    		},
    		removeEvents: function () {
    		    for (var i = 0, detach; detach = this._events[ i ]; ++i) {
    		      detach();
    		    }
    		    this._events.splice(0);
    		}
    }
    function escapeHtml(text) {
        return text.replace(/[<>"&]/g, function (match, pos, originalText) {
          switch (match) {
            case '<': return '&lt;';
            case '>': return '&gt;';
            case '&': return '&amp;';
            case '\'': return '&quot;';
          }
        });
      }
    window[nameSpace] =  {
    		instances:[],
    	    init: function (option) {
    	    	this.destroy(option.id);
    	        var instance = new component(option);//构建控件对象
    	        this.instances[ option.id ] = instance;
    	    },
    	    destroy: function (id) {
    	        var instance = this.instances[ id ];
    	        if (instance) instance.destroy();
    	        delete this.instances[ id ];
    	      }
    		};
})();
